package com.service.impl;

import com.dao.DepartmentDao;
import com.dao.UserDao;
import com.pojo.SysRole;
import com.pojo.SysUser;
import com.service.SysLogService;
import com.service.UserService;
import com.util.BCryptPasswordEncoderUtils;
import com.util.ConstUtils;
import com.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.Principal;
import java.util.*;

/**
 * @author mornd
 * @date 2020/11/12 - 14:05
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private SysLogService sysLogService;

    //判断用户登录
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据登录名查询user
        SysUser loginUser = userDao.findByName(username);
        //用户不存在
        if(loginUser == null) return null;

        //默认系统开始运行进行的操作 start
        //打印系统操作日志
        sysLogService.deleteSysLogByOverFolw();
        //end

        List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
        //遍历角色列表并赋值
        for (SysRole role : loginUser.getRoleList()) {
            authorities.add(new SimpleGrantedAuthority(role.getRoleCode()));
        }
        //返回User对象
        return new User(loginUser.getUserName(),
                loginUser.getPassword(),
                loginUser.getStatus() == 1,
                true,true,true,
                    authorities);
    }
    //查询用户列表
    public List<SysUser> findUserList(UserVo userVo) {
        return userDao.findUserList(userVo);
    }

    //根据deptId查询员工数量 判断该部门是否可以删除
    public int checkDeptByUser(Integer deptId) {
        return userDao.checkDeptByUser(deptId);
    }

    //添加用户
    public Map<String,Object> addUser(SysUser sysUser, Principal principal) {
        Map<String,Object> maps = new HashMap<String, Object>();
        if(findUserInfoByUserName(sysUser.getUserName()) != null){
            maps.put(ConstUtils.EXIST,true);
            maps.put(ConstUtils.MESSAGE,"该登录名称已重复，请更换用户名！");
        }else{
            maps.put(ConstUtils.EXIST,false);
            //根据当前登录用户名查询用户信息
            SysUser loginUser = findUserInfoByUserName(principal.getName());
            //创建日期
            sysUser.setCreateDate(new Date());
            //创建人id
            sysUser.setCreatedBy(loginUser.getId());
            //默认密码000
            sysUser.setPassword(BCryptPasswordEncoderUtils.encode(ConstUtils.DEFAULT_PASSWORD));
            //默认userType
            //x sysUser.setUserType(ConstUtils.DEFAULT_USERTYPE);
            if(userDao.addUser(sysUser) > 0){
                //给用户添加默认角色 ROLE_USER
                userDao.addByDefaultRole(sysUser.getId(),ConstUtils.DEFAULT_ROLE);
                maps.put(ConstUtils.SUCCESS,true);
                maps.put(ConstUtils.MESSAGE,"添加用户成功！");
            }else{
                maps.put(ConstUtils.SUCCESS,true);
                maps.put(ConstUtils.MESSAGE,"添加用户失败，请重试！");
            }
        }
        return maps;
    }

    //修改用户
    public Map<String,Object> updateUser(SysUser sysUser,Principal principal) {
        Map<String,Object> maps = new HashMap<String, Object>();
        //根据登录名称查询登录对象
        SysUser findUser = findUserInfoByUserName(sysUser.getUserName());
        //1.如果根据登录名称查询的用户不为空 则表示该登录名称已经存在 不可再添加
        //2.如果从数据库中查询出来的用户id不等于修改对象的id 则表示该用户名本就是该用户的无需向用户提示用户名存在
        if(findUser != null && findUser.getId() != sysUser.getId()){
            maps.put(ConstUtils.EXIST,true);
            maps.put(ConstUtils.MESSAGE,"该登录名称已重复，请更换用户名！");
        }else {
            maps.put(ConstUtils.EXIST, false);
            SysUser loginUser = findUserInfoByUserName(principal.getName());
            sysUser.setModifyDate(new Date());
            sysUser.setModifyBy(loginUser.getId());
            if(userDao.updateUser(sysUser) > 0){
                maps.put(ConstUtils.SUCCESS,true);
                maps.put(ConstUtils.MESSAGE,"修改用户成功！");
            }else{
                maps.put(ConstUtils.SUCCESS,false);
                maps.put(ConstUtils.MESSAGE,"修改用户失败，请重试！");
            }
        }
        return maps;
    }

    public boolean deleteUser(Integer userId) {
        //查询用户所占角色个数
        int count = userDao.findUserByRoleCount(userId);
        int delCount = 0;
        if(count > 0){
            //删除用户在用户角色表中的信息
            delCount = userDao.deleteDelUserByUserRole(userId);
        }
        //删除用户信息
        delCount += userDao.deleteUser(userId);
        //如果删除个数大于查询的个数则删除用户成功
        return delCount > count ? true : false;
    }

    //给用户添加角色
    public boolean addRoleByuserId(List<Integer> ids, Integer userId,Principal principal) {
        //先清空该用户的所有角色
        try {
            SysUser loginUser = findUserInfoByUserName(principal.getName());
            SysUser sysUser = new SysUser();
            //设置修改id
            sysUser.setId(userId);
            //设置修改时间
            sysUser.setModifyDate(new Date());
            //设置修改人
            sysUser.setModifyBy(loginUser.getId());
            //如果修改用户的角色中包含1、2则改用户的userType修改为1（管理员）
            /*x if(ids.contains(1) || ids.contains(2)){
                sysUser.setUserType(1);
            }else{
                sysUser.setUserType(2);
            }*/
            userDao.updateUser(sysUser);
            userDao.deleteDelUserByUserRole(userId);
            userDao.addRoleByuserId(ids,userId);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    //根据用户名称查询用户信息
    public SysUser findUserInfoByUserName(String userName) {
        return userDao.findUserInfoByUserName(userName);
    }

    //根据用户名查询用户
    public SysUser findUserById(Integer id) {
        return userDao.findUserById(id);
    }
}
